package com.tom.user.utils;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.tom.common.exception.CustomException;
import com.tom.user.entity.User;
import com.tom.user.mapper.UserMapper;
import com.tom.user.model.Constant;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * @author longjiang
 * @date 2020-03-26 11:21 上午
 * @description
 **/
@Component
public class UserUtil {
    private UserMapper userMapper;

    @Autowired
    public UserUtil(UserMapper userMapper) {
        this.userMapper = userMapper;
    }

    /**
     * 获取当前登录用户
     * @return
     */
    public User getCurrentLoggedUser() {
        String token = SecurityUtils.getSubject().getPrincipal().toString();

        // 解密token
        String username = JwtUtil.getClaim(token, Constant.USERNAME);

        User user = userMapper.selectOne(new QueryWrapper<User>().lambda().eq(User::getUsername,username));

        if (user == null ) {
            throw new CustomException("该账号不存在.");
        }

        return user;
    }

    /**
     * 获取当前登录用户id
     * @return
     */
    public Integer getCurrentLoggedId() {
        return getCurrentLoggedUser().getId();
    }

    /**
     * 获取当前登录用户token
     * @return
     */
    public String getCurrentLoggedToken() {
        return SecurityUtils.getSubject().getPrincipal().toString();
    }

    public String getCurrentLoggedUsername() {
        String token = SecurityUtils.getSubject().getPrincipal().toString();
        return JwtUtil.getClaim(token,Constant.USERNAME);
    }

}
